
/************************************************************************/
/*     	File Name:	TableS5.do		      								*/
/*     	Date:   	June 2025       		            				*/
/*      Author: 	Juan Acevedo-Ossa		                        	*/
/*      Purpose:   Replication file for "The Indirect Effects of	    */
/*				   Structural Power										*/
/*      Input Files:  gvcnousnoch.csv, gvconlyus.csv gvconlych.csv		*/	
/*                    gvcall.csv panel_unga.csv                                	*/	
/*      Output File:   "TableS1.rtf"                                     */
/*      Total Processing time:  8 hrs 42 minutes                        */
/*      Machine:  16.0 GB RAM - Intel Core i7 @ 2.50 GHz 16 cores       */
/************************************************************************/

*Open a log file: the values of F-test will can be accessed inside the log file once the estimation is completed 
log using tableS5.txt, text
 
timer clear
timer on 1

**************************************
*RUN PROGRAM FIRST                    *
**************************************

drop _all

pr drop _all

set more off

spmatrix clear

macro drop _all

capture matrix drop _all




program define splag_ll





if "$estimation"== "sarar" {

    args lnf mu rho1 rho2 rho3 lambda sigma

    tempvar A rSL1 rSL2 rSL3 rSE

    * Define spatially lagged dependent variables
    gen double `rSL1' = `rho1' * SL11
    gen double `rSL2' = `rho2' * SL21
    gen double `rSL3' = `rho3' * SL31

    * Use precomputed SE instead of matrix multiplication
    gen double `rSE' = `lambda' * SE1  // Now uses the variable SE

    * Define spatial lag matrices
    scalar p1 = `rho1'
    scalar p2 = `rho2'
    scalar p3 = `rho3'
    scalar lam = `lambda'

    matrix p1W1 = p1 * W1
    matrix p2W2 = p2 * W2
    matrix p3W3 = p3 * W3
    matrix lamW4 = lam * W4  // Spatial error matrix

    * Compute determinant adjustment for log-likelihood
    matrix IpW = I_n - p1W1 - p2W2 - p3W3
    matrix IpW_err = I_n - lamW4

    qui gen double `A' = ln(det(IpW)) + ln(det(IpW_err)) / $nobs if _n == 1
    scalar A = `A'

    * Compute log-likelihood
    qui replace `lnf' = A + ln(normalden($ML_y1 - `rSL1' - `rSL2' - `rSL3' - `rSE' - `mu', 0, `sigma'))
	
}


if "$estimation"== "sar" {

	args lnf mu rho1 rho2 rho3 sigma
	tempvar A rSL1 rSL2 rSL3 /* rSL4 */
	gen double `rSL1'=`rho1'*SL11
	gen double `rSL2'=`rho2'*SL21
	gen double `rSL3'=`rho3'*SL31

	scalar p1 = `rho1'
	scalar p2 = `rho2'
	scalar p3 = `rho3'

	matrix p1W1 = p1*W1
	matrix p2W2 = p2*W2
	matrix p3W3 = p3*W3

	matrix IpW = I_n - p1W1 - p2W2- p3W3

	qui gen double `A' = ln(det(IpW))/$nobs if _n == 1
	scalar A = `A'
	qui replace `lnf'= A + ln(normalden($ML_y1-`rSL1'-`rSL2'-`rSL3'-`mu', 0, `sigma'))


}

	



end




**************************************
*LOAD MATRICES                       *
**************************************


cd "`c(current_do)'" 

*All countries but China and the US
import delimited "Data\GVC matrices\gvcnousnoch.csv", varnames(nonames) clear
qui sum v1
global nobs = r(N)
mkmat v1-v$nobs, matrix(W1)
matrix I_n = I($nobs)

*Only the US
drop _all
import delimited "Data\GVC matrices\gvconlyus.csv", clear
mkmat v1-v$nobs, matrix(W2)

*Only China
drop _all
import delimited "Data\GVC matrices\gvconlych.csv", clear
mkmat v1-v$nobs, matrix(W3)


* Define a spatial weights matrix for the error term
import delimited "Data\GVC matrices\gvcall.csv", clear
mkmat v1-v$nobs, matrix(W4)  // W4 represents spatial diffusion of errors



**************************************
*SELECT VARS                     *
**************************************


global time year
global unit country_code

local j = 1



forvalues j=1/2 {

   

    if `j'== 1 {
        global dv StateDep
        global Y alignusimp
        global X lalignusimp laidusgdplog sanct_stock ltradegdpuslog polyarchy pop_log loggdppercapita corruption_control imf atop right_wing dip_visits_usa unsc_non_p developing
		
    }
    else if `j' == 2 {
        global dv US_CH_Diff
        global Y alignuschdiff
        global X lalignuschdiff laidusgdplog sanct_stock ltradegdpuslog polyarchy pop_log loggdppercapita corruption_control imf atop right_wing dip_visits_usa unsc_non_p developing
    }




local i =1

forvalues i=1/3 {

    if `i' == 1 {
	    drop _all
        import delimited "Data\panel_unga.csv", clear
		egen country_code = group(countrycodes), label
        sort year countrycodes

		global est "_SAR_FE" 
        global effect "fe"
        global estimation "sar"
		global model "$dv$est"

    }  
    if `i' == 2 {
		drop _all
        import delimited "Data\panel_unga.csv", clear
		egen country_code = group(countrycodes), label
        sort year countrycodes
		global est "_SARAR_RE" 
		global model "$dv$est"
        global effect "re"
        global estimation "sarar"
    }  
    if `i' == 3 {
		drop _all
        import delimited "Data\panel_unga.csv", clear
		egen country_code = group(countrycodes), label
        sort year countrycodes
		global est "_SARAR_FE"
		global model "$dv$est"
        global effect "fe"
        global estimation "sarar"
    }  






**************************************
*CREATE LAG SPATIAL VARIABLES        *
**************************************

    * Create Y-variable as a matrix (vector)
    mkmat $Y, matrix(Y)

    * Create 1st spatial-lag in matrix and then save as variable also
    matrix SL1 = W1*Y
    svmat SL1, n(SL1)

    * Create 2nd spatial-lag in matrix and then save as variable also
    matrix SL2 = W2*Y
    svmat SL2, n(SL2)

    * Create 3rd spatial-lag in matrix and then save as variable also
    matrix SL3 = W3*Y
    svmat SL3, n(SL3)
	
    * Run OLS to get initial residuals **after accounting for spatial    lags   of Y**
    qui regress $Y $X SL1 SL2 SL3
    predict res_adjusted, residuals
	
	mkmat res_adjusted, matrix(ResMat)

    * Create the spatially lagged error term
	matrix SE = W4 * ResMat
	svmat SE, n(SE)
	
	
	
	
**************************************
*      APPLY DEMEANED fe       *
**************************************

if "$effect"== "fe" {

global SL SL11 SL21 SL31 SE1

* Step 1: Compute Means for Fixed Effects
bysort $unit ($time): egen Y_mean = mean($Y)
replace $Y = $Y - Y_mean
drop Y_mean

* Demean independent variables in $X
foreach var in $X {
    bysort $unit ($time): egen `var'_mean = mean(`var')
    replace `var' = `var' - `var'_mean
    drop `var'_mean
}

* Demean spatial lags in $SL
foreach var in $SL {
    bysort $unit ($time): egen `var'_mean = mean(`var')
    replace `var' = `var' - `var'_mean
    drop `var'_mean
}



}


if "$estimation"== "sarar" {


    **************************************
    * MODEL 2 *
    **************************************

    * PRODUCE STARTING VALUES VIA OLS
    qui regress $Y $X 
	
    global nobs=e(N)
    matrix OLSb=e(b)
    global OLSsigma=e(rmse)

    * ESTIMATE SPATIAL LAG MODEL
    * Designate model to estimate
	ml model lf splag_ll (mu: $Y=$X) (rho1:) (rho2:) (rho3:) (lambda:) (sigma:)

* Specify starting values
	ml init OLSb
	ml init rho1:_cons=0
	ml init rho2:_cons=0
	ml init rho3:_cons=0
	ml init lambda:_cons=0
	ml init sigma:_cons=$OLSsigma

	ml max, trace
	estimates store $model
	estat ic

}






if "$estimation"== "sar" {

**************************************
    * estimation 1 *
    **************************************

    * PRODUCE STARTING VALUES VIA OLS
    qui regress $Y $X
    global nobs=e(N)
    matrix OLSb=e(b)
    global OLSsigma=e(rmse)

    * ESTIMATE SPATIAL LAG estimation
    * Designate estimation to estimate
    ml model lf splag_ll (mu: $Y=$X) (rho1:) (rho2:) (rho3:) (sigma:) /*(rho4:)*/

    * Specify starting values
    ml init OLSb
    ml init rho1:_cons=0
    ml init rho2:_cons=0
    ml init rho3:_cons=0
    * ml init rho4:_cons=0
    ml init sigma:_cons=$OLSsigma
    * ml max, difficult trace
    ml max, trace
	estimates store $model
	estat ic
	


}

	
}

}


timer off 1
timer list
log close



esttab StateDep_SAR_FE StateDep_SARAR_RE StateDep_SARAR_FE US_CH_Diff_SAR_FE US_CH_Diff_SARAR_RE US_CH_Diff_SARAR_FE, /// 
	mgroups("StateDep" "StateDep" "StateDep" "USChnDiff" "USChnDiff" "USChnDiff", pattern(1 1 1 1 1 1)) /// 
    mtitles("SAR FE" "SARAR RE" "SARAR FE" "SAR FE" "SARAR RE" "SARAR FE") ///
    cells("b(star fmt(4))" se(par fmt(4))) ///
    modelwidth(10) nodepvars ///
    varlabels(lalignusimp "State Dept Y(t-1)" ///
			  lalignuschdiff "Diff USCH Y(t-1)" ///
              lidealpointusimp "Ideal Point Y(t-1)" ///		  
              polyarchy "Democracy" ///
              pop_log "log(Population)" ///
              loggdppercapita "log(GDP per capita)" ///
              corruption_control "Control of corruption" ///
              imf "IMF commitment" ///
              right_wing "Right Wing" ///
              unsc_non_p "UNSC member" ///
              developing "Developing" ///
			  laidusgdplog "log(USAID/GDP)" ///
              sanct_stock "Sanctions" ///
              ltradegdpuslog "TradeUS/GDPlog (t-1)" ///
              atop "Alliances" ///
              dip_visits_usa "Diplomatic") ///
    order(lalignusimp lalignuschdiff polyarchy pop_log loggdppercapita corruption_control ///
          imf right_wing unsc_non_p developing laidusgdplog sanct_stock ltradegdpuslog ///
           atop dip_visits_usa) ///
    stats(N aic bic ll, fmt(%9.3f) label("Observations" "AIC" "BIC" "LL")) ///
    title("mSTAR models of vote coincidence") ///
    addnotes("* p-value < 0.10; ** p-value < 0.05 level; *** p-value < 0.01 level.")





	
	